﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using Business;
using System.Configuration;
using System.Net;
using Business.FlowOperation;

public partial class WebPubManager_FlowLinkEdit : PageBase
{
    private WorkFlowPubSetting wfpsTemp = new WorkFlowPubSetting();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            lblFlowName.Text = Request["datatype"];
            if (!string.IsNullOrEmpty(Request["id"]))
            {
                DataTable dt = wfpsTemp.GetFlowLink(Request["id"],"");
                if (dt.Rows.Count > 0)
                {
                    txtTitle.Text = dt.Rows[0]["TITLE"].ToString();
                    txtLinkHref.Text = dt.Rows[0]["LINKEHREF"].ToString();
                    txtImgSrc.Text = dt.Rows[0]["IMGSRC"].ToString();
                    

                }
            }
        }
    }

    protected void btnRefer_Click(object sender, EventArgs e)
    {
        string strId = Request["id"];
        string strImgName = string.Empty;
        string fileName = string.Empty;
        string strName = string.Empty;
        string fileName_s = string.Empty;
        string webFilePath_s = string.Empty;
        string picstr = FileImage.PostedFile.FileName;//要上传的文件全路径
        if (!string.IsNullOrEmpty(picstr))
        {
            string strSecond = DateTime.Now.ToLongTimeString().ToString();   // 20:16:16 
            strSecond = strSecond.Replace(":", "");
            string strYear = DateTime.Now.Year.ToString();               // 获取年份   // 2010   
            string strMonth = DateTime.Now.Month.ToString();              // 获取月份   // 3  
            string strDay = DateTime.Now.Day.ToString();                // 获取当日   // 11
            strImgName = strYear + strMonth + strDay + strSecond;
            FileInfo file = new FileInfo(picstr);
            fileName = file.Name;  // 文件名称
            strName = fileName.Substring(0, fileName.IndexOf("."));
            strName = strName + strImgName + file.Extension; ;// 组合成新的缩略图文件名称
            string path = Server.MapPath("uploadimg//");//文件夹new_pic的物理路径
            path = path.Replace("WebPubManager", "image");
            if (Directory.Exists(path) == false)//判断文件夹是否存在
                Directory.CreateDirectory(path);//创建文件夹
            webFilePath_s = path + strName;　　// 服务器端缩略图路径
            if (!btnUp_Click1(webFilePath_s))
            {
                fileName_s = "";
            }
            else
            {
                Common.ConfigHelper config = new Common.ConfigHelper(true);
                string ResServerPath = config.GetAppSettingsValue("UploadFile");
                string strServername = Request.Url.Authority;
                fileName_s = "http://" + strServername + ResServerPath + strName;
            }      

        }
        if (!string.IsNullOrEmpty(txtTitle.Text.Trim()))
        {
            if (strId == null || strId == "")
            {
                wfpsTemp.InsertFlowLink(Request["flowid"], txtTitle.Text.Trim(), fileName_s, txtLinkHref.Text.Trim());
            }
            else
            {
                wfpsTemp.UpdateFlowLink(strId, Request["flowid"], txtTitle.Text.Trim(), fileName_s, txtLinkHref.Text.Trim());
            }
            Response.Redirect("FlowLink.aspx?flowid=" + Request["flowid"] + "&datatype=" + Request["datatype"]);
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "<script>alert('标题不能为空')</script>");
        }

    }

    #region 返回菜单管理主界面
    /// <summary>
    /// 返回菜单管理主界面
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        Response.Redirect("FlowLink.aspx?flowid=" + Request["flowid"] + "&datatype=" + Request["datatype"]);
    }
    #endregion

    private void btnUp_Click()
    {
        string expicName = "jpg,img,gif,pci,bmp,pdf";//允许上传的图片的扩展名
        string[] strarray = expicName.Split(',');//把expicname的字符串以逗号（，）分隔，放到数组中
        bool IsNo = false;
        string picstr, exfileName, exfileNamepot;
        //string ftime, fsecond, fmonth, fyear, fminute, fdate, fnewName, fallName;
        picstr = FileImage.PostedFile.FileName;//要上传的文件全路径
        string filename = Path.GetFileName(picstr);//原文件名，包括扩展名
        FileInfo fname = new FileInfo(picstr);//复制 删除 移动和打开文件的实例方法
        exfileName = fname.Extension;//获取文件的扩展名,例如（.jpg）
        exfileNamepot = exfileName.Substring(1).ToLower();//获得exfileName字符串中从1开始到结束的字符串（获得扩展名除“.”的字符）
        int picrange = this.FileImage.PostedFile.ContentLength / 1024; //上传的文件大小（kb）

        if (picrange > 6300)
        {
            Response.Write("<script>alert('对不起，图片大小不能超过5MB');</script>");
        }
        else
        {
            //判断扩展名是否合法
            foreach (string k in strarray)
            {
                if (exfileNamepot.ToString().Trim() == k.ToString().Trim())
                {
                    IsNo = (IsNo || true);//如果是合法扩展名的图片，则IsNo为true；否则为false；
                    break;
                }
            }
            if (!(bool)IsNo)
            {
                //如果不是合法图片的扩展名
                Response.Write("<script>alert('对不起，图片格式不合法,\\n图片格式应为jpg、bmp、gif格式');</script>");
            }
            else
            {
                //如果是合法图片格式
                //fnewName = fyear + fmonth + fdate + ftime + fminute + fsecond;//新的文件名(无扩展名)
                //fallName = fnewName + exfileName;//新的文件名（包含扩展名）

                string path = Server.MapPath("uploadimg//");//文件夹new_pic的物理路径
                path = path.Replace("WebPubManager", "image");
                if (Directory.Exists(path) == false)//判断文件夹是否存在
                    Directory.CreateDirectory(path);//创建文件夹
                path += filename;//fallName;//上传后的文件物理路径

                FileImage.PostedFile.SaveAs(path);//将要上传的文件保存到指定的路径下和文件名,path为物理路径
                path = "image/uploadimg" + filename;// fallName;//保存到数据库里的文件路径
            }
        }

    }

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="webFilePath_s">图片要上传的物理路径以名称</param>
    /// <!--add by zhongjian 20100311-->
    public bool btnUp_Click1(string webFilePath_s)
    {
        bool Flag = false;
        string expicName = "jpg,img,gif,pci,bmp,pdf";//允许上传的图片的扩展名
        string[] strarray = expicName.Split(',');//把expicname的字符串以逗号（，）分隔，放到数组中
        bool IsNo = false;
        string picstr, exfileName, exfileNamepot;
        picstr = FileImage.PostedFile.FileName;//要上传的文件全路径
        string filename = Path.GetFileName(picstr);//原文件名，包括扩展名
        FileInfo fname = new FileInfo(picstr);//复制 删除 移动和打开文件的实例方法
        exfileName = fname.Extension;//获取文件的扩展名,例如（.jpg）
        exfileNamepot = exfileName.Substring(1).ToLower();//获得exfileName字符串中从1开始到结束的字符串（获得扩展名除“.”的字符）
        int picrange = this.FileImage.PostedFile.ContentLength / 1024; //上传的文件大小（kb）

        //判断扩展名是否合法
        foreach (string k in strarray)
        {
            if (exfileNamepot.ToString().Trim() == k.ToString().Trim())
            {
                IsNo = (IsNo || true);//如果是合法扩展名的图片，则IsNo为true；否则为false；
                break;
            }
        }
        if (!(bool)IsNo)
        {
            //如果不是合法图片的扩展名
            //string strError="<script>alert('对不起，图片格式不合法,\\n图片格式应为jpg、bmp、gif格式');</script>";
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "img", strError);
            Flag = false;
        }
        else
        {
            try
            {

                MakeThumbnail(picstr, webFilePath_s, 195, 32, "HW");     // 生成缩略图方法
                Flag = true;
                //System.Web.HttpContext.Current.Response.Write("图片上传成功.");
            }
            catch (Exception ex)
            {
                Flag = false;
                System.Web.HttpContext.Current.Response.Write("提示：图片上传失败，失败原因：" + ex.Message);
            }
        }
        return Flag;
    }

    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径（物理路径）</param>
    /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param> 
    /// <!--add 20100311-->
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth = width;
        int toheight = height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW"://指定高宽缩放（可能变形）               
                break;
            case "W"://指定宽，高按比例                   
                toheight = originalImage.Height * width / originalImage.Width;
                break;
            case "H"://指定高，宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                break;
            case "Cut"://指定高宽裁减（不变形）               
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
            new System.Drawing.Rectangle(x, y, ow, oh),
            System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
  
}




